package com.kingyea.app.market.appBaseInfo.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.kingyea.app.market.Preconditions;
import com.kingyea.app.market.apiInterface.service.ApiInterfaceService;
import com.kingyea.app.market.appBaseInfo.bean.AppBaseInfo;
import com.kingyea.app.market.appBaseInfo.bean.AppBaseInfoPublishVo;
import com.kingyea.app.market.appBaseInfo.bean.AppSyncBaseInfo;
import com.kingyea.app.market.appBaseInfo.bean.SyncObjVo;
import com.kingyea.app.market.appBaseInfo.dao.AppBaseInfoMapper;
import com.kingyea.app.market.appBaseInfo.service.AppBaseInfoService;
import com.kingyea.app.market.appBaseInfo.vo.AppBaseInfo2CreatePageInputVO;
import com.kingyea.app.market.appExtendInfo.bean.AppExtendInfo;
import com.kingyea.app.market.appExtendInfo.service.AppExtendInfoService;
import com.kingyea.app.market.client.UserServiceClient;
import com.kingyea.app.market.condition.AllCondition;
import com.kingyea.app.market.publishMarket.service.PublishMarketService;
import com.kingyea.app.market.syncMission.service.SyncMissionService;
import com.kingyea.app.market.userappmenu.service.UserAppMenuService;
import com.kingyea.app.market.utils.StateCode;
import com.kingyea.app.market.utils.page.PageInfo;
import com.kingyea.app.market.versionInfo.bean.VersionInfo;
import com.kingyea.app.market.versionInfo.service.VersionInfoService;
import com.kingyea.mobilepolice.system.Result;
import com.kingyea.mobilepolice.system.exception.BusinessException;
import com.kingyea.mobilepolice.user.bean.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author
 * @version v1.0.0
 * @description AppBaseInfo 实现类
 * @date Created in 2018-02-09 17:34:59
 */
@Service
@Transactional
public class AppBaseInfoServiceImpl implements AppBaseInfoService {

    private static final Logger LOGGER = LoggerFactory.getLogger(AppBaseInfoServiceImpl.class);

    @Resource
    private AppBaseInfoMapper appBaseInfoMapper;

    @Autowired
    private VersionInfoService versionInfoService;

    @Autowired
    private AppExtendInfoService appExtendInfoService;

    @Autowired
    private AppBaseInfoService appBaseInfoService;

    @Autowired
    private UserServiceClient userServiceClient;

    @Autowired
    private PublishMarketService publishMarketService;

    @Autowired
    private ApiInterfaceService apiInterfaceService;

    @Autowired
    private SyncMissionService syncMissionService;

    @Autowired
    private UserAppMenuService userAppMenuService;

    /**
     * 通过ID查找对象
     *
     * @param appCode
     * @return
     */
    @Override
    public AppBaseInfo getById(String appCode) throws Exception {
        return this.appBaseInfoMapper.getById(appCode);
    }

    /**
     * 列表
     *
     * @param
     * @return
     */
    @Override
    public Object list(Map<String, Object> appBaseInfo) throws Exception {
        PageInfo.startPage(appBaseInfo);
        return PageInfo.getPageInfo(appBaseInfoMapper.list(appBaseInfo));
    }

    /**
     * 删除
     *
     * @param appCode
     * @return
     */
    @Override
    public int deleteById(String appCode) throws Exception {
        if (org.apache.commons.lang3.StringUtils.isBlank(appCode)) {
            throw new BusinessException(StateCode.NO_ARGUMENT_ERROR);
        }
        appBaseInfoMapper.deleteById(appCode);
        return 1;
    }

    /**
     * 保存
     *
     * @param appBaseInfo
     * @return
     */
    @Override
    public AppBaseInfo save(AppBaseInfo appBaseInfo) throws Exception {
        if (org.apache.commons.lang3.StringUtils.isBlank(appBaseInfo.getAppCode())) {
            String appCode = UUID.randomUUID().toString().replaceAll("-", "");
            appBaseInfo.setAppCode(appCode);
        }

        if (org.apache.commons.lang3.StringUtils.isBlank(appBaseInfo.getUserId())) {
            // 保存创建人信息
            Result<User> currentUserInfo = userServiceClient.getCurrentUserInfo();
            User data = currentUserInfo.getData();
            appBaseInfo.setUserId(data.getUserId());
            appBaseInfo.setUserName(data.getName());
        }
        Preconditions.checkArgument(appBaseInfoMapper.save(appBaseInfo) > 0, StateCode.SYSTEM_ERROR);
        return appBaseInfo;
    }

    /**
     * 更新
     *
     * @param appBaseInfo
     * @return
     */
    @Override
    public AppBaseInfo update(AppBaseInfo appBaseInfo) throws Exception {
        if (org.apache.commons.lang3.StringUtils.isBlank(appBaseInfo.getAppCode())) {
            throw new BusinessException(StateCode.NO_ARGUMENT_ERROR);
        }
        appBaseInfoMapper.update(appBaseInfo);
        return appBaseInfo;
    }


    @Override
    public Object getList(Map<String, Object> appBaseInfo) throws Exception {
        PageInfo.startPage(appBaseInfo);
        return PageInfo.getPageInfo(appBaseInfoMapper.getlist(appBaseInfo));
    }

    @Override
    public List<AppBaseInfo> getByAppType(String appType) {
        List<AppBaseInfo> byAppType = null;
        byAppType = appBaseInfoMapper.getByAppType(appType);
        return byAppType;
    }

    @Override
    public List<AppBaseInfo> getByMarket(String appMarket) {
        // TODO Auto-generated method stub
        List<AppBaseInfo> byMarket = null;
        byMarket = appBaseInfoMapper.getByMarket(appMarket);
        return byMarket;
    }

    @Override
    public Object listInfo(Map<String, Object> appBaseInfo) throws Exception {
        PageInfo.startPage(appBaseInfo);
        return PageInfo.getPageInfo(appBaseInfoMapper.listInfo(appBaseInfo));
    }

    @Override
    public Object versionList(Map<String, Object> appBaseInfo) throws Exception {
        // TODO Auto-generated method stub
        PageInfo.startPage(appBaseInfo);
        return PageInfo.getPageInfo(appBaseInfoMapper.versionList(appBaseInfo));
    }

    @Override
    public Object appList(Map<String, Object> appBaseInfo) throws Exception {
        PageInfo.startPage(appBaseInfo);
        return PageInfo.getPageInfo(appBaseInfoMapper.appList(appBaseInfo));
    }

    @Override
    public Object appList_new(Map<String, Object> appBaseInfo) throws Exception {
        PageInfo.startPage(appBaseInfo);
        return PageInfo.getPageInfo(appBaseInfoMapper.appList_new(appBaseInfo));
    }

    @Override
    public AppSyncBaseInfo getSyncList(Map<String, Object> appBaseInfo) throws Exception {
        // TODO Auto-generated method stub

        return appBaseInfoMapper.getSyncList(appBaseInfo);
    }

    @Override
    @Transactional
    public AppSyncBaseInfo save(AppSyncBaseInfo appSyncBaseInfo) throws Exception {

        VersionInfo versionInfo = versionInfoService.getById(appSyncBaseInfo.getVersionInfo().getId());
        AppExtendInfo appExtendInfo = appExtendInfoService.getById(appSyncBaseInfo.getAppExtendInfo().getId());
        AppBaseInfo appBaseInfo = appBaseInfoMapper.getById(appSyncBaseInfo.getAppCode());
        if (null != versionInfo) {
            appExtendInfoService.update(appSyncBaseInfo.getAppExtendInfo());//更新应用扩展信息
        } else {
            appExtendInfoService.save(appSyncBaseInfo.getAppExtendInfo());//保存应用扩展信息
        }
        if (null != appExtendInfo) {
            versionInfoService.update(appSyncBaseInfo.getVersionInfo());//更新应用版本信息
        } else {
            versionInfoService.save(appSyncBaseInfo.getVersionInfo());//保持应用版本信息
        }
        if (null != appBaseInfo) {
            appBaseInfo = JSONObject.parseObject(JSONObject.toJSONString(appSyncBaseInfo), AppBaseInfo.class);
            appBaseInfoMapper.update(appBaseInfo);//更新应用基本信息
        } else {
            appBaseInfo = JSONObject.parseObject(JSONObject.toJSONString(appSyncBaseInfo), AppBaseInfo.class);
            appBaseInfoMapper.save(appBaseInfo);//保存应用基本信息
        }
        return appSyncBaseInfo;
    }

    @Override
    @Transactional
    public SyncObjVo save(SyncObjVo syncObjVo) throws Exception {
        //判断本地是否存在该应用，不存在：保存，存在：更新
        AppBaseInfo baseInfo = appBaseInfoMapper.getById(syncObjVo.getAppBaseInfo().getAppCode());
        AppExtendInfo extendInfo = appExtendInfoService.getByAppCode(syncObjVo.getAppBaseInfo().getAppCode());
//		VersionInfo versionInfo = versionInfoService.getById(syncObjVo.getVersionInfo().getId());//由于 version 表中id 为 uuid，每次生成id 都不等，不可使用这种方式
        Map<String, Object> versionMap = new HashMap();
        versionMap.put("appCode", syncObjVo.getAppBaseInfo().getAppCode());
        versionMap.put("versionType", syncObjVo.getVersionInfo().getVersionType());
        versionMap.put("version", syncObjVo.getVersionInfo().getVersion());
        PageInfo versionPageInfo = (PageInfo) versionInfoService.list(versionMap);
        if (null != extendInfo) {
            appExtendInfoService.update(syncObjVo.getAppExtendInfo());//更新应用扩展信息
        } else {
            appExtendInfoService.save(syncObjVo.getAppExtendInfo());//保存应用扩展信息
        }
        if (versionPageInfo.getTotal() == 1) {
            versionInfoService.update(syncObjVo.getVersionInfo());//更新应用版本信息
        } else if (versionPageInfo.getTotal() == 0) {
            VersionInfo versionInfo = syncObjVo.getVersionInfo();
//			versionInfo.setId(syncObjVo.getVersionInfo().getId());
            versionInfoService.save(syncObjVo.getVersionInfo());//保持应用版本信息
        } else {
            System.out.println("请检查应用版本是否冲突....");
        }
        if (null != baseInfo) {
//			appBaseInfo = JSONObject.parseObject(JSONObject.toJSONString(syncObjVo), AppBaseInfo.class);
            appBaseInfoMapper.update(syncObjVo.getAppBaseInfo());//更新应用基本信息
        } else {
//			appBaseInfo = JSONObject.parseObject(JSONObject.toJSONString(syncObjVo), AppBaseInfo.class);
            appBaseInfoMapper.save(syncObjVo.getAppBaseInfo());//保存应用基本信息
        }
        return syncObjVo;
    }

    @Override
    public PageInfo<AppBaseInfoPublishVo> searchPpublishApp(AllCondition condition) throws Exception {
        PageInfo.startPage(JSON.parseObject(JSON.toJSONString(condition), Maps.<String, Object>newHashMap().getClass()));
        return PageInfo.getPageInfo(appBaseInfoMapper.searchPpublishApp(condition));
    }

    @Override
    public PageInfo<AppBaseInfoPublishVo> searchPublishVerify(AllCondition condition) throws Exception {
        PageInfo.startPage(JSON.parseObject(JSON.toJSONString(condition), Maps.<String, Object>newHashMap().getClass()));
        return PageInfo.getPageInfo(appBaseInfoMapper.searchPublishVerify(condition));
    }

    @Override
    public AppBaseInfo2CreatePageInputVO addApp(AppBaseInfo2CreatePageInputVO appBaseInfo2CreatePageInputVO) throws Exception {
        System.out.println(JSON.toJSONString(appBaseInfo2CreatePageInputVO));
        VersionInfo androidVersion = appBaseInfo2CreatePageInputVO.getAndroidVersion();// 安卓版本信息
        VersionInfo iosVersion = appBaseInfo2CreatePageInputVO.getIosVersion();// ios版本信息
        VersionInfo webVersion = appBaseInfo2CreatePageInputVO.getWebVersion();// web版本信息
        List<VersionInfo> versionInfos = Lists.newArrayList(androidVersion, iosVersion, webVersion);
        String appTerminal = "";// 适用终端 1 web, 2 ios, 3 android 多个用逗号分割
        for (VersionInfo versionInfo : versionInfos) {// 拼接适用终端
            if (null != versionInfo && (org.apache.commons.lang3.StringUtils.isNotBlank(versionInfo.getAccessUrl()) || org.apache.commons.lang3.StringUtils.isNotBlank(versionInfo.getInstallPackage()))) {
                switch (versionInfo.getVersionType()) {//版本类型 1：web,2:ios3:android
                    case 1:
                        appTerminal = appTerminal + "1,";
                        break;
                    case 2:
                        appTerminal = appTerminal + "2,";
                        break;
                    case 3:
                        appTerminal = appTerminal + "3,";
                        break;
                }
            }
        }
        if (appTerminal.endsWith(",")) {
            appTerminal = appTerminal.substring(0, appTerminal.length() - 1);
        }
        appBaseInfo2CreatePageInputVO.setAppTerminal(org.apache.commons.lang3.StringUtils.isBlank(appTerminal) ? null : appTerminal);

        if (org.apache.commons.lang3.StringUtils.isBlank(appBaseInfo2CreatePageInputVO.getAppCode())) {
            appBaseInfoService.save(appBaseInfo2CreatePageInputVO);
        } else {
            appBaseInfoService.update(appBaseInfo2CreatePageInputVO);
        }
        AppExtendInfo appExtendInfo = new AppExtendInfo();
        appExtendInfo.setAppCode(appBaseInfo2CreatePageInputVO.getAppCode());
        appExtendInfo.setAppTerminal(org.apache.commons.lang3.StringUtils.isBlank(appTerminal) ? null : appTerminal);
        if (org.apache.commons.lang3.StringUtils.isBlank(appBaseInfo2CreatePageInputVO.getAppCode())) {
            appExtendInfoService.save(appExtendInfo);
        } else {
            appExtendInfoService.update(appExtendInfo);
        }


        for (VersionInfo versionInfo : versionInfos) {
            if (null != versionInfo && (!StringUtils.isEmpty(versionInfo.getAccessUrl()) || !StringUtils.isEmpty(versionInfo.getInstallPackage()))) {// todo version 保存逻辑需要判断空 未完成
                versionInfo.setAppCode(appBaseInfo2CreatePageInputVO.getAppCode());
                versionInfo.setVersion(org.apache.commons.lang3.StringUtils.isBlank(versionInfo.getVersion()) ? "初始版本" : versionInfo.getVersion());
                versionInfo.setCurrentVersion(1);//是否当前版本：0否  ； 1是
                if (org.apache.commons.lang3.StringUtils.isBlank(versionInfo.getId())) {
                    versionInfoService.save(versionInfo);
                } else {
                    versionInfoService.update(versionInfo);
                }

                switch (versionInfo.getVersionType()) {//版本类型 1：web,2:ios3:android
                    case 1:
                        appBaseInfo2CreatePageInputVO.setWebVersion(versionInfo);
                        break;
                    case 2:
                        appBaseInfo2CreatePageInputVO.setIosVersion(versionInfo);
                        break;
                    case 3:
                        appBaseInfo2CreatePageInputVO.setAndroidVersion(versionInfo);
                        break;
                }
            }
        }
        //添加时没有market。。。怎么发布
//		PublishMarket publishMarket = new PublishMarket();
//		publishMarket.setAppCode(appBaseInfo.getAppCode());
//		publishMarket.setMarketCode(appBaseInfo.getAppMarket());
//		publishMarket.setApplictionType(appBaseInfo.getAppType());
//		publishMarketService.save(publishMarket);
        return appBaseInfo2CreatePageInputVO;
    }

    @Override
    public int deleteAllAppInfoByAppCode(String appCode) throws Exception {
        if (org.apache.commons.lang3.StringUtils.isBlank(appCode)) {
            throw new BusinessException(StateCode.NO_ARGUMENT_ERROR);
        }
        appBaseInfoService.deleteById(appCode);// app基础信息
        appBaseInfoService.deleteAppAuthorizationByAppCode(appCode);// app 授权信息
        versionInfoService.deletesByAppCode(appCode);// app版本信息
        publishMarketService.deletesByAppCode(appCode);// app发布信息
        appExtendInfoService.deletesByAppCode(appCode);// app扩展信息
        apiInterfaceService.deletesByAppCode(appCode); // app关联接口信息
        syncMissionService.deletesByAppCode(appCode);// app同步信息
        userAppMenuService.deletesByAppCode(appCode);// 用户已下载app列表信息

        return 1;
    }

    @Override
    public Object deleteAppAuthorizationByAppCode(String appCode) throws Exception {
        if (org.apache.commons.lang3.StringUtils.isBlank(appCode)) {
            throw new BusinessException(StateCode.NO_ARGUMENT_ERROR);
        }
        return appBaseInfoMapper.deleteAppAuthorizationByAppCode(appCode);
    }
}

